package com.blb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.entity.Company;
import com.blb.entity.Role;
import com.blb.entity.User;
import com.blb.service.ICompanyService;
import com.blb.service.IRoleService;
import com.blb.service.IUserService;
import com.blb.utils.ShiroUtils;
import com.blb.utils.UUIDUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("register")
public class RegisterController {

    @Resource
    private ICompanyService companyService;

    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;


    @RequestMapping("aa")
    public String register(){
        return"system/registers";
    }

    @ResponseBody
    @RequestMapping("getUser")
    public User getUserByUserName(String username){

        User user = userService.getUserByUsername(username);

        return user;

    }
    @ResponseBody
    @RequestMapping("getCompany")
    public Company getCompanyByCompanyName(String companyname){


        Company company = companyService.getOne(new QueryWrapper<Company>().eq("company_name", companyname));

        return company;

    }



    @RequestMapping("addUserAndCompany")
    public String  addUserAndCompany( User user , Company company, Model model){



        //生成随机的公司id和用户id,混淆数
        String companyId = UUIDUtils.getId();
        String userId = UUIDUtils.getId();
        String salt = UUIDUtils.getId();

        user.setSalt(salt);
        user.setId(userId);

        //给公司设置注册时间
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
        String creatTime = dateFormat.format(date);
        company.setCreatTime(creatTime);

        user.setCompanyId(companyId);
        company.setId(companyId);

        //给公司添加状态
        company.setCompanyStatus("on");
        companyService.save(company);

        //给密码加密
        String pas = ShiroUtils.enPas(user.getPassWord(), salt);
        user.setPassWord(pas);

        //查询次数默认为0
        int querytime = 0;
        user.setQueryTimes(querytime);

        user.setPId("0");
        user.setUserStatus("1");
        userService.save(user);


        //注册给用户添加管理员角色
        roleService.addUserAndRole(userId,1);

        return "redirect:/";

    }



}
